package com.duanjw.springframework.util;

import com.duanjw.springframework.anno.Component;

import java.io.File;
import java.lang.reflect.InvocationTargetException;

/**
 * 注解
 *
 * @author duanjw
 */
public class AnnotationConfigApplicationContext {
    String path = null;

    public void scan(String packageName) {
        path = this.getClass().getResource("/").getPath();
        packageName = packageName.replaceAll(".", "/");
        File file = new File(path + "/" + packageName);
        showFile(file);
    }

    public void showFile(File file) {
        //判断是否为文件 ，如是打印文件名
        if (file.isFile()) {
            String absolutePath = file.getAbsolutePath();
            absolutePath = absolutePath.replace(path, "").replaceAll("/", ".");
            String name = absolutePath.replace(".class", "");
            try {
                Class<?> clazz = Class.forName(name);
                Component annotation = clazz.getAnnotation(Component.class);
                if (annotation != null) {
                    try {
                        Object instance = clazz.getDeclaredConstructor().newInstance();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            //如不是文件，则将文件夹下的所有文件夹定义为数组
            File[] files = file.listFiles();

            for (int i = 0; i < files.length; i++) {
                //循环进行调用
                showFile(files[i]);
            }
        }
    }

    public static void main(String[] args) {
        new AnnotationConfigApplicationContext().scan("com.duanjw.springframework");
    }
}
